const emojiHTML = (() => {
    const emojis = [
        {emoji: "😏", description: "奸笑"},
        {emoji: "😂", description: "哭笑"},
        {emoji: "🤭", description: "捂脸笑"},
        {emoji: "🥺", description: "哀求"},
        {emoji: "😎", description: "酷"},
        {emoji: "😀", description: "笑脸"},
        {emoji: "😁", description: "露齿笑"},
        {emoji: "😃", description: "笑"},
        {emoji: "😄", description: "笑"},
        {emoji: "😍", description: "爱心眼"},
        {emoji: "🥳", description: "庆祝"},
        {emoji: "😜", description: "调皮"},
        {emoji: "😡", description: "生气"},
        {emoji: "😠", description: "怒"},
        {emoji: "🤬", description: "咒骂"},
        {emoji: "😢", description: "哭"},
        {emoji: "😭", description: "放声大哭"},
        {emoji: "😞", description: "沮丧"},
        {emoji: "😔", description: "失望"},
        {emoji: "🤔", description: "思考"},
        {emoji: "😕", description: "疑问"},
        {emoji: "😝", description: "吐舌"},
        {emoji: "🙃", description: "颠倒的笑脸"},
        {emoji: "😇", description: "天使"},
        {emoji: "🤩", description: "星星眼"},
        {emoji: "😵", description: "晕"},
        {emoji: "😳", description: "害羞"},
        {emoji: "🤪", description: "疯狂"},
        {emoji: "😶", description: "沉默"},
        {emoji: "🫣", description: "惊讶"},
        {emoji: "❤️", description: "红心"},
        {emoji: "💖", description: "闪亮的爱心"},
        {emoji: "💘", description: "心动"},
        {emoji: "🥰", description: "爱心包围"},
        {emoji: "🐶", description: "狗"},
        {emoji: "🐱", description: "猫"},
        {emoji: "🐸", description: "青蛙"},
        {emoji: "🐯", description: "老虎"},
        {emoji: "🐵", description: "猴子"},
        {emoji: "🦁", description: "狮子"},
        {emoji: "🦊", description: "狐狸"},
        {emoji: "🐼", description: "熊猫"},
        {emoji: "🍕", description: "披萨"},
        {emoji: "🍔", description: "汉堡"},
        {emoji: "🍩", description: "甜甜圈"},
        {emoji: "🍎", description: "苹果"},
        {emoji: "🍉", description: "西瓜"},
        {emoji: "🍻", description: "啤酒"},
        {emoji: "🥤", description: "饮料"},
        {emoji: "🌍", description: "地球"},
        {emoji: "🌅", description: "日出"},
        {emoji: "🏖️", description: "度假"},
        {emoji: "🌈", description: "彩虹"},
        {emoji: "🌻", description: "向日葵"},
        {emoji: "🌸", description: "樱花"},
        {emoji: "⛰️", description: "山脉"},
        {emoji: "🏕️", description: "野营"},
        {emoji: "🎉", description: "庆祝"},
        {emoji: "🎂", description: "生日蛋糕"},
        {emoji: "🎁", description: "礼物"},
        {emoji: "🎃", description: "南瓜灯"},
        {emoji: "🎆", description: "烟花"},
        {emoji: "🥂", description: "干杯"}
    ];

    return emojis.map(item =>
        `<span class="emoji" title="${item.description}">${item.emoji}</span>`
    ).join('');
})();

function generatorCommentBoxHtml(articleId, replyCommentId, replyUserId, rootCommentId) {
    return `
    <div class="comment-box" data-id="1" > 
        <div class="editor" contenteditable="true" data-comment-placeholder="写下你的评论..."></div>
        <input type="hidden" value="${articleId}" class="articleId">
        <input type="hidden" value="${replyCommentId}" class="replyCommentId">
        <input type="hidden" value="${replyUserId}" class="replyUserId">
        <input type="hidden" value="${rootCommentId}" class="rootCommentId">
        <div class="error-message" style="display: none;">评论不能为空！</div>
        <div class="word-count">0/5000</div>
        <div class="toolbar">
            <div class="icons"> 
                <i class="far fa-smile emoji-btn"></i>
                <i class="fas fa-image image-btn"></i> 
                <input type="file" class="image-upload" accept="image/*" style="display: none;">
            </div>
            <div class="submit-btn">
                <button class="submit-comment">发布</button>
            </div>
        </div>
        <div class="emoji-picker">
            ${emojiHTML}
        </div>
    </div>
`
}

function generatorCommentHtml(comment) {
    return `
    <div class="comment-item" data-commentId="${comment.commentId}">
        <!-- 左侧头像部分 -->
        <div class="comment-left">
            <figure class="media-left">
                <p class="image is-48x48">
                    <img class="comment-avatar" src="${comment.avatar}" alt=""/>
                </p>
            </figure>
        </div>
        <!-- 右侧内容部分 -->
        <div class="comment-right">
            <div class="comment-top">
                <span class="comment-content">
                    <strong>
                        <a class="comment-nickname" target="_blank"
                           href="${comment.address}">${comment.nickname}</a>
                        <span class="tag is-dark user-auth">${comment.formT}</span>
                        <span class="tag is-info question-author"
                              style="display: ${comment.author ? '' : 'none'}">作者</span>
                    </strong>
                    <br/>
                    <span
                        class="comment-text ${comment.status ? '' : 'comment-del-text'}">${sanitizeContent(comment.content)}</span>
                </span>
            </div>
            <div class="comment-bottom">
                <span class="comment-btn-list">
                    <span class="comment-btn-left">
                        <span class="comment-time">${comment.dateTime}</span>
                    </span>
                    <span class="comment-btn-right" style="display: ${comment.status ? '' : 'none'}">
                        <span class="comment-del comment-item-margin"
                              style="display: ${comment.owner && comment.status ? '' : 'none'}">删除</span>
                        <span class="comment-comment comment-item-margin" style="display: ${comment.commentable ? '' : 'none'}">
                            <i class="fa-solid fa-message"></i>
                        </span>
                        <span class="comment-likeCount comment-item-margin">
                            <i class="fa-heart fa-regular ${comment.sessionUserLike ? 'fa-solid comment-is-like' : ''}"></i>
                            <span>${comment.likeCount}</span>
                        </span>
                        <span class="comment-share comment-item-margin">
                            <i class="fa-solid fa-share"></i>
                        </span>
                    </span>
                </span>
            </div>
            ${generatorCommentBoxHtml(comment.articleId, comment.commentId, comment.userId, comment.commentId)}
            ${childrenCommentHtml(comment.childrenComments, comment.commentId)}
        </div>
    </div>
    
    `
}

function generatorChildrenCommentHtml(childrenComment, rootCommentId) {
    return `
     <div class="comment-item" data-commentId="${childrenComment.commentId}">
        <!-- 左侧头像部分 -->
        <div class="comment-left">
            <figure class="media-left">
                <p class="image is-48x48">
                    <img class="comment-avatar" src="${childrenComment.avatar}" alt=""/>
                </p>
            </figure>
        </div>
        <!-- 右侧内容部分 -->
        <div class="comment-right">
            <div class="comment-top">
                <span class="comment-content">
                    <strong>
                        <a class="comment-nickname" target="_blank" href="${childrenComment.address}">${childrenComment.nickname}</a>
                        <span class="tag is-dark user-auth">${childrenComment.formT}</span>
                        <span class="tag is-info question-author" style="display: ${childrenComment.author ? '' : 'none'}">作者</span>
                    </strong>
                    <br/>
                    <span class="comment-text ${childrenComment.status ? '' : 'comment-del-text'}">${sanitizeContent(childrenComment.content)}</span>
                    <span class="comment-reply" data-replyCommentId="${childrenComment.parentCommentId}" 
                        style="display: ${childrenComment.parentCommentId !== rootCommentId ? '' : 'none'}">
                        <span class="comment-reply-line"></span>
                        <span class="comment-reply-frame">
                            <a target="_blank" href="${childrenComment.replyAddress}">
                                <i class="fa-solid fa-at"></i>
                                <img class="rounded-avatar" src="${childrenComment.replyAvatar}" alt="...">
                                <span>${childrenComment.replyNickname}</span>
                            </a>
                            <span class="comment-reply-content ${childrenComment.replyIdStatus ? '' : 'comment-del-text'}">
                                ${sanitizeContent(childrenComment.replyContent)}
                            </span>
                        </span>
                    </span>
                </span>
            </div>
            <div class="comment-bottom">
                <span class="comment-btn-list">
                    <span class="comment-btn-left">
                        <span class="comment-time">${childrenComment.dateTime}</span>
                        <!--<span class="comment-chat-list button is-small is-rounded is-light" data-chat-comment-id="${childrenComment.commentId}">
                            查看完整评论
                        </span>-->
                    </span>
                    <span class="comment-btn-right" style="display: ${childrenComment.status ? '' : 'none'}">
                        <span class="comment-del comment-item-margin" style="display: ${childrenComment.owner && childrenComment.status ? '' : 'none'}">删除</span>
                        <span class="comment-comment comment-item-margin" style="display: ${childrenComment.commentable ? '' : 'none'}">
                            <i class="fa-solid fa-message"></i>
                        </span>
                        <span class="comment-likeCount comment-item-margin">
                            <i class="fa-heart fa-regular ${childrenComment.sessionUserLike ? 'fa-solid comment-is-like' : ''}"></i>
                            <span>${childrenComment.likeCount}</span>
                        </span>
                        <span class="comment-share comment-item-margin">
                            <i class="fa-solid fa-share"></i>
                        </span>
                    </span>
                </span>
            </div>
            ${generatorCommentBoxHtml(childrenComment.articleId, childrenComment.commentId, childrenComment.userId, rootCommentId)}
        </div>
    </div>
    `
}

function questionCommentList(questionId, callback) {
    $("#comment-article").empty();
    $.ajax({
        url: `/comment/list/${questionId}`,
        type: 'GET',
        success: function (res) {
            if (res.code === 200) {
                var commentHtml = '';
                $.each(res.data, function (index, comment) {
                    commentHtml = commentHtml + generatorCommentHtml(comment)
                })

                $("#comment-article").append(commentHtml);
                callback();
            } else {
                showErrorToast(res.msg);
            }
        },
        error: function (err) {
            showErrorToast(err);
        }
    });
}

function childrenCommentHtml(childrenComments, commentId) {
    let childrenHtml = ''
    if (!childrenComments || childrenComments.length === 0) {
        return childrenHtml;
    }
    $.each(childrenComments, function (idx, childrenComment) {
        childrenHtml = childrenHtml + generatorChildrenCommentHtml(childrenComment, commentId);
    })
    return childrenHtml;
}

$(document).ready(function () {
    reload();
});

function reload() {
    const maxLength = 5000;


    $(document).on('click', '.comment-comment', function () {
        let $commentRight = $(this).closest('.comment-right');
        const replyName = $commentRight.children('.comment-top')
            .children('.comment-content')
            .children('strong')
            .children('a')
            .text();
        let $commentBox = $commentRight.children('.comment-box');
        $('.comment-box').not($commentBox).not('.comment-box-global').hide();
        $commentBox.children('.editor').attr('data-comment-placeholder', `@${replyName}`);
        $commentBox.toggle();
    })

    // 表情选择器显示/隐藏
    $(document).on('click', '.emoji-btn', function () {
        const $toolbar = $(this).closest('.toolbar');
        const $picker = $toolbar.siblings('.emoji-picker');
        $picker.toggle();
    });

    // 选择表情
    $(document).on('click', '.emoji', function () {
        const emoji = $(this).text();
        const $editor = $(this).closest('.comment-box').find('.editor');
        $editor.append(emoji);
        $(this).closest('.emoji-picker').hide();
        updateWordCount($editor);
    });

    // 图片上传
    $(document).on('click', '.image-btn', function () {
        $(this).siblings('.image-upload').click();
    });

    // 点赞
    $(document).on('click', '.comment-likeCount', function () {
        // 未登录不可以点赞
        let $likeElement = $(this);
        const commentId = parseInt($likeElement.closest('.comment-item').data('commentid'));
        commentLikeCount(commentId, () => {
            let $like = $likeElement.children('i');
            let $count = $likeElement.children('span');
            const count = parseInt($count.text());
            if ($like.hasClass('fa-solid comment-is-like')) {
                $count.text(count - 1);
            } else {
                $count.text(count + 1);
            }
            $like.toggleClass('fa-solid comment-is-like');
        })
    });

    // 分享
    $(document).on('click', '.comment-share', function () {
        // 未登录不可以删除
        let $shareElement = $(this);
        let $commentItem = $shareElement.closest('.comment-item');
        const text = $commentItem.children('.comment-right')
            .find('.comment-top .comment-text')
            .text();
        const pageAuthor = $("#create-user-nickname").text();
        let pageURL = window.location.href;
        const commentIdIndex = pageURL.indexOf('#commentId-');
        if (commentIdIndex !== -1) {
            pageURL = pageURL.substring(0, commentIdIndex + '#commentId-'.length)
                + $commentItem.data("commentid");
        } else {
            pageURL = pageURL + '#commentId-' + $commentItem.data("commentid");
        }
        shareArticleOrComment(text, pageAuthor, pageURL);
    });

    // 删除
    $(document).on('click', '.comment-del', function () {
        // 未登录不可以删除
        let $delElement = $(this);
        let $commentItem = $delElement.closest('.comment-item');
        const commentId = parseInt($commentItem.data('commentid'));
        commentDel(commentId, () => {
            $commentItem.find('.comment-right .comment-top .comment-text')
                .addClass('.comment-del-text')
                .text('已删除!');
            $delElement.closest('.comment-btn-right').hide();
            $(`span[data-replyCommentId=${commentId}]`)
                .find('.comment-reply-content ')
                .addClass('comment-del-text')
                .text('已删除!');
        })
    });

    $(document).on('change', '.image-upload', function () {
        const files = this.files;
        const $editor = $(this).closest('.comment-box').find('.editor');
        // TODO 未登录应该不能上传图片，待认证
        const formData = new FormData();
        // 将文件添加到 FormData 对象
        Array.from(files).forEach(file => {
            formData.append('file', file);
        });
        uploadFile(formData, (data) => {
            const imgHtml = `<img class="img-preview" src="${data.url}" alt="${data.newName}">`;
            $editor.append(imgHtml);
        })

    });

    // 提交评论
    $(document).on('click', '.submit-comment', function () {
        let $commentBox = $(this).closest('.comment-box');
        const articleId = parseInt($commentBox.find(".articleId").val());
        const replyCommentId = parseInt($commentBox.find(".replyCommentId").val());
        const replyUserId = parseInt($commentBox.find(".replyUserId").val());
        const rootCommentId = parseInt($commentBox.find(".rootCommentId").val());
        const $editor = $commentBox.find('.editor');
        let content = $editor.html().trim();
        if (content === "<br>") {
            content = "";
        }

        if (!content) {
            // 如果评论内容为空，显示错误消息并添加红色边框
            const $errorMessage = $(this).closest('.comment-box').find('.error-message');
            $errorMessage.show();
            $editor.addClass('warning');
            return;
        }

        console.log('评论内容：', content, articleId, replyCommentId, replyUserId);

        const commentData = JSON.stringify({
            replyUserId: replyUserId,
            content: content,
            parentCommentId: replyCommentId,
        });
        submitComment(articleId, commentData, comment => {
            if (replyCommentId === 0) {
                $("#comment-article")
                    .append(generatorCommentHtml(comment));
            } else {
                const targetDiv = $(`div[data-commentId="${rootCommentId}"]`);
                if (targetDiv.length > 0) {
                    targetDiv.children('.comment-right').children('.comment-box')
                        .after(generatorChildrenCommentHtml(comment, rootCommentId))
                }
            }
        })
        $commentBox.toggle();
        $editor.empty();
        updateWordCount($editor)
        $editor.removeClass('warning');
        $(this).closest('.comment-box').find('.error-message').hide();
    });

    // 更新字数和显示警告
    function updateWordCount($editor) {
        const $wordCount = $editor.closest('.comment-box').find('.word-count');
        const content = $editor.text().trim();
        const contentLength = content.length;

        // 更新字数显示
        $wordCount.text(`${contentLength}/${maxLength}`);

        // 如果字数超过限制，添加警告
        if (contentLength > maxLength) {
            $editor.addClass('warning');
            $wordCount.addClass('warning');
        } else {
            $editor.removeClass('warning');
            $wordCount.removeClass('warning');
        }
    }

    // 监听输入事件来实时更新字数
    $(document).on('input', '.editor', function () {
        const $editor = $(this);
        updateWordCount($editor);
    });

    // 点击页面其他地方关闭表情选择器
    $(document).on('click', function (e) {
        if (!$(e.target).closest('.emoji-btn, .emoji-picker').length) {
            $('.emoji-picker').hide();
        }
    });
}

function submitComment(articleId, commentData, callback) {
    $.ajax({
        url: `/comment/${articleId}`,
        contentType: "application/json",
        type: 'POST',
        data: commentData,
        success: function (res) {
            if (res.code === 200) {
                console.log("评论提交成功")
                callback(res.data);
            } else if (res.code === 401) {
                // window.location.href = "/login.html"
                showErrorToast(res.msg);
            } else {
                console.log("错误:" + res)
            }
        },
        error: function (err) {
            console.log("错误:" + err)
        }
    });
}

function commentLikeCount(commentId, callback) {
    $.ajax({
        url: `/comment/like-count/${commentId}`,
        type: 'PUT',
        success: function (res) {
            if (res.code === 200) {
                callback();
            } else if (res.code === 401) {

            } else {
                console.log("错误:" + res)
            }
        },
        error: function (err) {
            console.log("错误:" + err)
        }
    });
}

function commentDel(commentId, callback) {
    $.ajax({
        url: `/comment/${commentId}`,
        type: 'DELETE',
        success: function (res) {
            if (res.code === 200) {
                callback()
            } else if (res.code === 401) {
            } else {
                console.log("错误:" + res)
            }
        },
        error: function (err) {
            console.log("错误:" + err)
        }
    });
}

function shareArticleOrComment(text, author, linkUrl) {
    $("#shareModal").addClass("is-active");
    $('#copyBtn').removeAttr('disabled');
    var shareText = `
          内容：[ ${text} ] <br>
          作者：${author} <br>
          链接：${linkUrl} <br>`
    $("#share-text").html(shareText)
}

function sanitizeContent(content) {
    // 创建一个临时的 div 元素，并设置其 HTML 内容
    const $tempDiv = $('<div>').html(content);

    // 查找所有的 img 标签，遍历并为其添加样式和点击事件
    $tempDiv.find('img').each(function () {
        $(this).css({
            'max-width': '100px',
            'max-height': '100px',
            'border-radius': '5px',
            'margin': '5px'
        });
        $(this).addClass('img-preview')
    });

    // 返回处理后的 HTML 内容
    return $tempDiv.html();
}

function uploadFile(formData, callback) {
    // 使用 AJAX 上传文件
    $.ajax({
        url: '/file/upload',
        type: 'POST',
        data: formData,
        processData: false,  // 禁止 jQuery 自动处理数据
        contentType: false,  // 禁止 jQuery 设置 Content-Type
        success: function (res) {
            callback(res.data)
        },
        error: function (xhr, status, error) {
            console.error('上传失败:', error);
            // 可在此处显示错误提示
        }
    });
}

function scrollToComment(articleId, commentId) {
    const targetComment = $("div[data-commentid='" + commentId + "']")
        .children('.comment-right')
        .children('.comment-top')
    if (targetComment.length) {
        targetComment.addClass('highlight');
        setTimeout(() => targetComment.removeClass('highlight'), 2000);
        $('html, body').animate({scrollTop: targetComment.offset().top - $(window).height() / 2 + targetComment.outerHeight() / 2}, 500);
    } else {
        questionCommentList(articleId, () => {
            scrollToComment(articleId, commentId);
        });
    }
}